package com.duan.laugh.mp.controller;

import cn.hutool.core.util.StrUtil;
import com.duan.laugh.mp.config.WxMpConfiguration;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

/**
 * <p>
 * 授权登录
 * </p>
 *
 * @author liutf
 * @since 2019-10-28
 */
@RestController
@RequestMapping("/wx")
@Slf4j
@AllArgsConstructor
public class WechatController {

    /**
     * 获取网页授权 URL
     *
     * @param returnUrl
     * @return
     */
    @GetMapping("/authorize")
    public String authorize(@RequestParam(value = "returnUrl", required = false) String returnUrl) {
        if (StrUtil.isNullOrUndefined(returnUrl)) returnUrl = "https://duanjw.utools.club/wx/userInfo";
        WxMpService wxMpService = WxMpConfiguration.getMpServices().get("wxa50010df48eec30c");
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(returnUrl, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
        log.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
        return "redirect:" + redirectURL;
    }

    /**
     * 微信回调
     *
     * @param code
     * @param returnUrl
     * @param response
     * @throws Exception
     */
    @GetMapping("/userInfo")
    public void userInfo(@RequestParam("code") String code,
                         @RequestParam("state") String returnUrl,
                         HttpServletResponse response) throws Exception {
        log.info("【微信网页授权】code={}", code);
        log.info("【微信网页授权】state={}", returnUrl);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            WxMpService wxMpService = WxMpConfiguration.getMpServices().get("wxa50010df48eec30c");
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
            log.info("【微信网页授权】 用户信息={}", wxMpUser);
        } catch (WxErrorException e) {
            log.info("【微信网页授权】{}", e);
            throw new Exception(e.getError().getErrorMsg());
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        log.info("【微信网页授权】openId={}", openId);
        response.sendRedirect("https://www.baidu.com");
//        return "redirect:" + returnUrl + "?openid=" + openId;
    }
}
